// @author: caoshi
// @date: 2021-05-15 09:30
package main

import (
	"bytes"
	"demo06_json_data_submit/src/bean"
	"demo06_json_data_submit/src/resp"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

/**
	获取请求body中的数据(json)转换为字符串
 */
func GetDataString(req *http.Request) string {
	result, err := ioutil.ReadAll(req.Body)
	if err != nil {
		return "{\"code\": 1,\"msg\": \"failed\"}"
	}
	return bytes.NewBuffer(result).String()
}

// 处理用户注册
func register(w http.ResponseWriter, req *http.Request) {
	fmt.Println("处理用户注册...")

	//result, err := ioutil.ReadAll(req.Body)
	//if err != nil {
	//	res, _ := json.Marshal(resp.Error("注册信息有误"))
	//	w.Write(res)
	//}

	data := GetDataString(req)
	user := bean.User{}
	// 将json字符串转成user对象
	_ = json.Unmarshal([]byte(data), &user)
	fmt.Println(user)

	checkMsg := "尊敬的" + user.UserName + "用户, 欢迎您注册, 感谢^_^. 首次登陆请使用验证码"
	info := bean.RegisSuccess{
		CheckCode: 10090,
		CheckMsg: checkMsg,
	}
	// return resp.Success("注册成功", user)
	//res, _ := json.Marshal(resp.Success("注册成功", info))
	infoJson, _ := json.Marshal(info)
	infoStr := string(infoJson)
	fmt.Println("infoStr = ", infoStr)
	succResp := resp.Success("注册成功", infoStr)
	fmt.Println(succResp)
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	fmt.Fprintln(w, succResp)
}


func main() {
	server := http.Server{Addr:":8081"}
	http.HandleFunc("/user/register", register)
	server.ListenAndServe()
}



